import React, { useState, useCallback, useEffect } from 'react';
import { Button, Card, List, Radio, Row, Col, Popconfirm, Modal, Tag, message, Spin, notification } from 'antd';
import { LoadingOutlined, MessageOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import AuthComponent from '@/components/Authorized/AuthComponent';
import moment from 'moment';
import { useRequest } from '@umijs/hooks';
import styles from './index.less';
import History from './History';
import { getMsgList, updateMsgRead } from '../../service';
import { parseMessage } from '../../utils';
import { router } from 'umi';
import { parse } from 'querystring';
import InfiniteScroll from 'react-infinite-scroller';

const size = 3;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { CheckableTag } = Tag;
const scopeArr = ['all', 'unread', 'read'];

const MessageCenter = ({ msgType, oRadiotype, setoRadiotype, leftRef }) => {
  const [scope, setScope] = useState(1);
  const [scrollNum, setScrollNum] = useState(1);
  const { loading, data, loadingMore, reload, loadMore: runLoadMore } = useRequest(
    ({ pagination = {} } = {}) => {
      const page = pagination.current ? pagination.current + 1 : 1;
      // return msgType ? getMsgList({ page, msgState: scope, size, msgType }) : Promise.resolve({});
      return msgType ? getMsgList({ page, msgState: scope, size }) : Promise.resolve({});
    },
    {
      loadMore: true,
      initialData: { list: [] },
      refreshDeps: [msgType, scope, oRadiotype],
    },
  );

  useEffect(() => {
    setScope(scopeArr.indexOf(oRadiotype));
  }, [oRadiotype])

  const { list, pagination: { current, totalPages, total = 0 } = {} } = data;

  const loadMore = (
    <div
      style={{
        textAlign: 'center',
        marginTop: 16,
      }}
    >
      <Button
        onClick={runLoadMore}
        loading={loadingMore}
        style={{
          paddingLeft: 48,
          paddingRight: 48,
          marginBottom: 24,
        }}
      >
        {loading ? (
          <span>
            <LoadingOutlined /> 加载中...
          </span>
        ) : (
            '加载更多'
          )}
      </Button>
    </div>
  );

  const { run: read } = useRequest(updateMsgRead, {
    manual: true,
    onSuccess() {
      setoRadiotype('read');
      leftRef && leftRef.current && leftRef.current.load && leftRef.current.load();
    },
  });

  const onMessageCLick = useCallback(
    (msg, noRead) => {
      if (msg.moduleUrl) {
        let resourceStr = window.localStorage.getItem('resource');
      // /banksearchSystem/inPortBaggageManagement/lessBaggageManagement 少收
      // /banksearchSystem/inPortBaggageManagement/internalMissingManagement 内务缺失
      //         AHL  少收；---行查子平台-进港少收行李管理；
      // LOS  内物缺失；---行查子平台-进港内物缺失管理；
      // 需要把事故单号带过去查询出查看的事故单展示在列表
      // 消息title   少收行李到期结案提醒
      if (msg.msgTitle === '少收行李到期结案提醒') {
        let toaccidentId = ''; //事故单号
        if(msg.msgContent.indexOf('AHL') > -1){
          if(resourceStr.indexOf('"path":"/banksearchSystem/inPortBaggageManagement/lessBaggageManagement') == -1){
            return  notification.info({
              message: '您当前无权限进行查看',
            });
          }
          let sliceStartIndex = msg.msgContent.indexOf('AHL')
          toaccidentId = msg.msgContent.slice(sliceStartIndex,sliceStartIndex+17);
          window.sessionStorage.setItem('isFromCompensate','1');
          router.push({
            pathname: '/banksearchSystem/inPortBaggageManagement/lessBaggageManagement',
            state: {
              accidentId: toaccidentId
            }
          });
        } 
        if(msg.msgContent.indexOf('LOS') > -1){
          if(resourceStr.indexOf('"path":"/banksearchSystem/inPortBaggageManagement/internalMissingManagement') == -1){
            return  notification.info({
              message: '您当前无权限进行查看',
            });
          }
          let sliceStartIndex = msg.msgContent.indexOf('LOS')
          toaccidentId = msg.msgContent.slice(sliceStartIndex,sliceStartIndex+17);
          window.sessionStorage.setItem('isFromCompensate','1');
          router.push({
            pathname: '/banksearchSystem/inPortBaggageManagement/internalMissingManagement',
            state: {
              accidentId: toaccidentId
            }
          });
        }
      }else{
        if(resourceStr.indexOf(`${msg.moduleUrl.split('?')[0]}`) == -1 || !AuthComponent.getAuth('compensation.audit.viewDetail')){
          return  notification.info({
            message: '您当前无权限进行查看',
          });
        };
        let query = {};
        if (~msg.moduleUrl.indexOf('?')) {
          query = parse(msg.moduleUrl.split('?')[1])
        };
        sessionStorage.setItem('firstLoad', '1');
        let sendDate = msg.msgDate.substring(0, 10);
        let compensationAuditState = { ...query,sendDate: sendDate,  flightDate: msg.flightDate, flightNo: msg.flightNo };
        window.localStorage.setItem('compensationAuditState',JSON.stringify(compensationAuditState));
        router.push({
          pathname: msg.moduleUrl.split('?')[0],
          state: compensationAuditState
        });
      }
        // let query = {}
        // if (~msg.moduleUrl.indexOf('?')) {
        //   query = parse(msg.moduleUrl.split('?')[1])
        // }
        // sessionStorage.setItem('firstLoad', '1')
        // router.push({
        //   pathname: msg.moduleUrl.split('?')[0],
        //   state: { ...query, flightDate: msg.flightDate, flightNo: msg.flightNo }
        // });
      }
      if (noRead) {
        read({ msgId: msg.msgId, msgType: '' });
      }
    },
    [read],
  );

  const readAll = useCallback(() => {
    read({ msgId: 0, msgType });
  }, [msgType, read]);

  const [historyShow, setHistoryShow] = useState(false);
  const toggleHistory = useCallback(() => {
    setHistoryShow(!historyShow);
  }, [historyShow]);

  const handleInfiniteOnLoad = () => {
    if ((list.length) && (+totalPages - +current)) {
      runLoadMore();
      setScrollNum(scrollNum + 1);
    } else {
      message.success('已加载全部数据');
    }
  }

  return (
    <>
      <Row justify="end" style={{ marginTop: 16 }}>
        <Col span={16}>
          <RadioGroup value={oRadiotype} onChange={e => setoRadiotype(e.target.value)}>
            <RadioButton key="unread" onClick={() => setScope(1)} value="unread">
              未读
            </RadioButton>
            <RadioButton key="read" onClick={() => setScope(2)} value="read">
              已读
            </RadioButton>
            <RadioButton key="all" onClick={() => setScope(0)} value="all">
              全部
            </RadioButton>
          </RadioGroup>
          <Button style={{ marginLeft: 8 }} icon="clock-circle" onClick={toggleHistory}>
            历史记录
          </Button>
          <Modal
            title="历史记录"
            visible={historyShow}
            width="72%"
            footer={false}
            onCancel={toggleHistory}
            bodyStyle={{ backgroundColor: '#f0f2f5' }}
          >
            <History msgType={msgType} />
          </Modal>
        </Col>
        <Col span={8} style={{ textAlign: 'right' }}>
          {
            scope === 2
              ? null
              : <Popconfirm
                title={`全部${scope === 1 ? '未读' : ''}消息共${total}条，标为已读后，消息将不再显示未读标识，确定继续吗？`}
                arrowPointAtCenter="bottom"
                onConfirm={readAll}
                onCancel={() => { }}
                okText="确定"
                cancelText="取消"
                placement="bottomRight"
              >
                <Button icon="check">全部标记为已读</Button>
              </Popconfirm>
          }

        </Col>
      </Row>
      <InfiniteScroll
        initialLoad={false}
        loadMore={handleInfiniteOnLoad}
        hasMore={true}
        pageStart={+scrollNum}
        useWindow={true}
        threshold={1}
      >
        <List
          style={{ marginTop: 16 }}
          size="large"
          split={false}
          loading={list.length === 0 ? loading : false}
          rowKey="msgId"
          itemLayout="vertical"
          grid={{ gutter: 24, column: 1 }}
          // loadMore={(list.length) && (+totalPages - +current) ? loadMore : null}
          dataSource={list}
          renderItem={item => (
            <List.Item key={item.msgId}>
              <Card
                bordered={false}
                title={
                  <span>
                    {item.msgState === 1 && (
                      <CheckableTag checked color="blue">
                        未读
                      </CheckableTag>
                    )}
                    {item.msgTitle}
                  </span>
                }
                extra={item.msgDate}
                actions={[
                  <div
                    onClick={() => onMessageCLick(item, item.msgState === 1)}
                    style={{ textAlign: 'left', padding: '0 24px' }}
                  >
                    <span>立即查看</span>
                    <span style={{ float: 'right' }}>&gt;</span>
                  </div>,
                ]}
              >
                <div className={styles.listContent}>
                  <div className={styles.description}>{parseMessage(item.msgContent)}</div>
                  {msgType === 'self' && (
                    <div className={styles.extra}>
                      <em>{moment(item.updatedAt).format('YYYY-MM-DD HH:mm')}</em>
                      <span style={{ float: 'right' }}>
                        <MessageOutlined
                          style={{
                            marginRight: 6,
                          }}
                        />
                      16条评论
                    </span>
                    </div>
                  )}
                </div>
              </Card>
            </List.Item>
          )}
        >
          {loadingMore && !!((list.length) && (+totalPages - +current)) && (
            <div className={styles.listLoadingContainer}>
              <Spin />
            </div>
          )}
        </List>
      </InfiniteScroll>
    </>
  );
};

export default MessageCenter;
